class Solution {
    public boolean isValid(String s) {
        Stack<Integer> stack = new Stack<>();
        stack.ensureCapacity(s.length());
        for (int i = 0; i < s.length(); i++) {
            int index = "({[)}]".indexOf(s.charAt(i));
            if (index <= 2) {
                stack.push(index);
            } else if (stack.size() == 0 || stack.pop() != index % 3) {
                return false;
            }
        }
        return stack.size() == 0;
    }
}